//
//  FileManager+Helpers.swift
//  OnionBrowser2
//
//  Copyright © 2012 - 2023, Tigas Ventures, LLC (Mike Tigas)
//
//  This file is part of Onion Browser. See LICENSE file for redistribution terms.
//

import Foundation

public extension FileManager {

	var cacheDir: URL? {
		urls(for: .cachesDirectory, in: .userDomainMask).last
	}

	var docsDir: URL? {
		urls(for: .documentDirectory, in: .userDomainMask).last
	}

	/**
	 Store data in <appdir>/Library/Caches/tor (Library/Caches/ is for things that can persist between
	 launches -- which we'd like so we keep descriptors & etc -- but don't need to be backed up because
	 they can be regenerated by the app)
	 */
	var torDir: URL? {
		guard let url = cacheDir?.appendingPathComponent("tor", isDirectory: true) else {
			return nil
		}

		// Create tor data directory if it does not yet exist.
		try? createSecureDirIfNotExists(at: url)

		return url
	}

	var authDir: URL? {
		guard let url = torDir?.appendingPathComponent("auth", isDirectory: true) else {
			return nil
		}

		// Create onion v3 auth directory if it does not yet exist.
		try? createSecureDirIfNotExists(at: url)

		return url
	}

	var ptDir: URL? {
		guard let url = torDir?.appendingPathComponent("pt_state", isDirectory: true) else {
			return nil
		}

		try? createSecureDirIfNotExists(at: url)

		return url
	}


	func createSecureDirIfNotExists(at url: URL) throws {
		// Try to remove it, if it is *not* a directory.
		if fileExists(atPath: url.path) {
			if !((try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false) {
				try removeItem(at: url)
			}
		}

		// Try to create it, and all its intermediate directories, if it doesn't
		// exist. Create with secure permissions.
		if !fileExists(atPath: url.path) {
			try createDirectory(
				at: url, withIntermediateDirectories: true,
				attributes: [.posixPermissions: NSNumber(value: 0o700)])
		}
	}

	func sizeOfItem(atPath path: String) -> Int64? {
		return (try? attributesOfItem(atPath: path))?[.size] as? Int64
	}
}
